package com.example.orchid.paper.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类
 * Created by Orchid on 2015-10-13.
 */
public class MD5Utils {


    public static String encrypt(String source) {
        // 用来将字节转换成 16 进制表示的字符
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        String target = "";

        if (source == null) {
            source = "";
        }

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source.getBytes());
            byte[] b = md.digest();
            char[] str = new char[16 * 2];


            int k = 0;

            for (int i = 0; i < 16; i++) {
                byte byte0 = b[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, >>> 为逻辑右移，将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
            }

            target = new String(str);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return target;
    }

}
